package controller

import (
	"context"
	"crypto/md5"
	"fmt"
	"time"
	v1 "wh-1-backend/api/v1"
	"wh-1-backend/internal/consts"
	"wh-1-backend/internal/model"
	"wh-1-backend/internal/service"
)

type cAuth struct{}

var Auth = cAuth{}

func (a *cAuth) Login(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
	user, err := service.Auth().LoginCheck(ctx, req)
	if err != nil {
		return
	}
	tokenStr := []byte(fmt.Sprintf("%d-%d", time.Now().UnixNano(), user.Id))
	tokenHash := md5.Sum(tokenStr)
	token := fmt.Sprintf("%x", tokenHash)
	err = service.User().SetCacheUser(ctx, token, user)
	if err != nil {
		return
	}
	res = &v1.LoginRes{Token: token}
	return
}

func (a *cAuth) Logout(ctx context.Context, req *v1.LogoutReq) (res *v1.LogoutRes, err error) {
	err = service.User().DelCacheUser(ctx, (ctx.Value(consts.AuthHeaderKey)).(string))
	return
}

func (a *cAuth) UserProfile(ctx context.Context, req *v1.UserProfileReq) (res *v1.UserProfileRes, err error) {
	res = &v1.UserProfileRes{}
	res.UserInfo = *service.Auth().GetUser(ctx)
	res.Password = "xxx--xxx"
	if service.Auth().IsAdmin(ctx) {
		res.Menus, err = service.Menu().Tree(ctx)
		if err != nil {
			return nil, err
		}
	} else {
		var ids []uint
		for _, role := range res.Roles {
			ids = append(ids, role.Id)
		}
		var menuList []*model.MenuTreeItem
		menuList, err = service.Menu().GetListByRoleId(ctx, ids)
		if err != nil {
			return
		}
		res.Menus = service.Menu().MakeTree(menuList)
	}
	return
}
